﻿using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Customer;
using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request.CustomerManager;
using Common.Contract.Customer.Response.CustomerManager;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Service;
using Common.Service.DataTables;
using SMECustomerWebsite.Core.Configuration;
using SMECustomerWebsite.Filters;
using SMECustomerWebsite.Models.ViewModels.ExportData;
using SMECustomerWebsite.Models.ViewModels.MSBO;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Web.Mvc;

namespace SMECustomerWebsite.Controllers
{
    public class MSBOController : ControllerBase
    {
        //
        // GET: /MSBO/
        [CustomActionFilter]
        [Authorize]
        public ActionResult ViewAll()
        {
            MSBOViewModel vm = new MSBOViewModel
            {
                CurrentUser = CurrentUserRecord,
            };
            return View(vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ViewAllData(DataTablesPageRequest pageRequest)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                FilterRecord filter = GetBaseFilter(pageRequest.SearchColumns);
                switch (CurrentUserRecord.GroupIdentifier)
                {
                    case "1":
                        filter.ContractType = pageRequest.SearchColumns[4];
                        filter.Email = pageRequest.SearchColumns[5];
                        filter.CusOpenDate = pageRequest.SearchColumns[6];
                        break;
                    case "2":
                        filter.ContractType = pageRequest.SearchColumns[3];
                        filter.Email = pageRequest.SearchColumns[4];
                        filter.CusOpenDate = pageRequest.SearchColumns[5];
                        break;
                    case "3":
                        if (CurrentUserRecord.Position == "HUB Manager")
                        {
                            filter.ContractType = pageRequest.SearchColumns[3];
                            filter.Email = pageRequest.SearchColumns[4];
                            filter.CusOpenDate = pageRequest.SearchColumns[5];
                        }
                        else
                        {
                            filter.ContractType = pageRequest.SearchColumns[2];
                            filter.Email = pageRequest.SearchColumns[3];
                            filter.CusOpenDate = pageRequest.SearchColumns[4];
                        }
                        break;
                    default:
                        break;
                }
                RetrieveListMsboRequest request = new RetrieveListMsboRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.MSBOController.ViewAllData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                var customerRecords = new RetrieveListMsboResponse();
                customerRecords = serviceClient.Proxy.RetrieveListMsbo(request);
                var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<UserRecord>() : customerRecords.Records;
                switch (CurrentUserRecord.GroupIdentifier)
                {
                    case "1":
                        pageResponse = new DataTableResponse
                        {
                            sEcho = pageRequest.Echo,
                            iTotalRecords = customerRecords.Page.TotalRecords,
                            sColumns = pageRequest.ColumnNames,
                            aaData = resultCustomer.Select(x => new object[]{
                                                                 x.Zone,
                                                                 x.Branch,
                                                                 x.Dao,
                                                                 x.FullName,
                                                                 x.ContractType,
                                                                 x.Email,
                                                                 x.StartWorkingDate,
                                                                 x.Dao
                        }).ToList()
                        };
                        break;
                    case "2":
                        pageResponse = new DataTableResponse
                        {
                            sEcho = pageRequest.Echo,
                            iTotalRecords = customerRecords.Page.TotalRecords,
                            sColumns = pageRequest.ColumnNames,
                            aaData = resultCustomer.Select(x => new object[]{
                                                                 x.Branch,
                                                                 x.Dao,
                                                                 x.FullName,
                                                                 x.ContractType,
                                                                 x.Email,
                                                                 x.StartWorkingDate,
                                                                 x.Dao
                        }).ToList()
                        };
                        break;
                    case "3":
                        if (CurrentUserRecord.Position.Equals("Hub Manager"))
                        {
                            pageResponse = new DataTableResponse
                            {
                                sEcho = pageRequest.Echo,
                                iTotalRecords = customerRecords.Page.TotalRecords,
                                sColumns = pageRequest.ColumnNames,
                                aaData = resultCustomer.Select(x => new object[]{
                                                                 x.Team,
                                                                 x.Dao,
                                                                 x.FullName,
                                                                 x.ContractType,
                                                                 x.Email,
                                                                 x.StartWorkingDate,
                                                                 x.Dao
                        }).ToList()
                            };
                        }
                        else
                        {
                            pageResponse = new DataTableResponse
                            {
                                sEcho = pageRequest.Echo,
                                iTotalRecords = customerRecords.Page.TotalRecords,
                                sColumns = pageRequest.ColumnNames,
                                aaData = resultCustomer.Select(x => new object[]{
                                                                 x.Dao,
                                                                 x.FullName,
                                                                 x.ContractType,
                                                                 x.Email,
                                                                 x.StartWorkingDate,
                                                                 x.Dao
                        }).ToList()
                            };
                        }
                        break;
                    default:
                        break;
                }

            }
            return Json(pageResponse);
        }

        [CustomActionFilter]
        [Authorize]
        public ActionResult ExportDataMSBO()
        {
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                RetrieveListMsboRequest request = new RetrieveListMsboRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.MSBOController.ExportDataMSBO"
                    },
                    Page = new PageRecord
                    {
                        //PageSize = pageRequest.DisplayLength,
                        //PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    CurrentUser = CurrentUserRecord,
                };
                var customerRecords = new RetrieveListMsboResponse();
                customerRecords = serviceClient.Proxy.RetrieveListMsbo(request);
                var resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<ExportMSBOViewModel>() : customerRecords.Records.Select(x => new ExportMSBOViewModel
                {
                    Dao = x.Dao,
                    UserName = x.UserName,
                    ContractType = x.ContractType,
                    Branch = x.Branch,
                    Zone = x.Zone,
                    StartWorkingDate = x.StartWorkingDate,
                    BranchCode = x.BranchCode,
                    Email = x.Email
                }).ToList();
                DataTable dt = new DataTable();
                dt = ToDataTable(resultCustomer);
                var fileName = "ListMSBO " + CurrentUserRecord.Branch + ".xlsx";
                ExportToExcel(dt, fileName);
            }
            return RedirectToAction("TotalCustomer", "CustomerManager");
        }

        #region Ajax method

        [Authorize]
        [HttpPost]
        public ActionResult ListBranch(string data)
        {
            List<BranchRecord> resultCustomer = new List<BranchRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveListBranchRequest request = new RetrieveListBranchRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    Dao = CurrentUserRecord
                };
                var customerRecords = new RetrieveListBranchResponse();
                customerRecords = serviceClient.Proxy.RetrieveListBranch(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<BranchRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Select(x => new
            {
                id = x.BranchId,
                text = x.BranchName
            });
            result = Json(objectItem);
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListBranchFreedom(string data)
        {
            List<BranchRecord> resultCustomer = new List<BranchRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                UserRecord Dao = new UserRecord
                {
                    GroupIdentifier = "1"
                };
                RetrieveListBranchRequest request = new RetrieveListBranchRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    Dao = Dao
                };
                var customerRecords = new RetrieveListBranchResponse();
                customerRecords = serviceClient.Proxy.RetrieveListBranch(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<BranchRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Where(x => x.Region != "VUNG 0").Select(x => new
            {
                id = x.BranchId,
                text = x.BranchName
            });
            result = Json(objectItem);
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListBranchForDaoManager(string data)
        {
            List<BranchRecord> resultCustomer = new List<BranchRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                UserRecord Dao = new UserRecord
                {
                    GroupIdentifier = "1"
                };
                RetrieveListBranchRequest request = new RetrieveListBranchRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    Dao = Dao
                };
                var customerRecords = new RetrieveListBranchResponse();
                customerRecords = serviceClient.Proxy.RetrieveListBranch(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<BranchRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Where(x => x.Region != "VUNG 0").Select(x => new
            {
                id = x.BranchId.Substring(x.BranchId.Length - 3),
                text = x.BranchName
            });
            result = Json(objectItem);
            return result;
        }
        [Authorize]
        [HttpPost]
        public ActionResult ListRegion(string data)
        {
            List<BranchRecord> resultCustomer = new List<BranchRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveListBranchRequest request = new RetrieveListBranchRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    Dao = CurrentUserRecord
                };
                var customerRecords = new RetrieveListBranchResponse();
                customerRecords = serviceClient.Proxy.RetrieveListBranch(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<BranchRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = from x in resultCustomer
                             group x by x.Region into g
                             select new
                             {
                                 id = g.Key,
                                 text = g.FirstOrDefault().Region
                             };
            result = Json(objectItem.ToList());
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListRegionFreedom(string data)
        {
            List<BranchRecord> resultCustomer = new List<BranchRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                UserRecord Dao = new UserRecord
                {
                    GroupIdentifier = "1"
                };
                RetrieveListBranchRequest request = new RetrieveListBranchRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    Dao = Dao
                };
                var customerRecords = new RetrieveListBranchResponse();
                customerRecords = serviceClient.Proxy.RetrieveListBranch(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<BranchRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = from x in resultCustomer
                             where x.Region != "VUNG 0"
                             group x by x.Region into g
                             select new
                             {
                                 id = g.Key,
                                 text = g.FirstOrDefault().Region
                             };
            result = Json(objectItem.ToList());
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListMSBOName(string data)
        {
            List<UserRecord> resultCustomer = new List<UserRecord>();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                FilterRecord record = new FilterRecord();
                RetrieveListMsboRequest request = new RetrieveListMsboRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = record
                };
                var customerRecords = new RetrieveListMsboResponse();
                Thread.Sleep(100 * int.Parse(data));
                customerRecords = serviceClient.Proxy.RetrieveListMsbo(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<UserRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Select(x => new
            {
                id = x.Dao,
                text = data.Equals("1") ? x.FullName : x.Dao
            });
            result = Json(objectItem);
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListMSBONameFreedom(string data)
        {
            List<UserRecord> resultCustomer = new List<UserRecord>();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UserRecord Dao = new UserRecord
                {
                    GroupIdentifier = "1",
                    Position = "Freedom"
                };
                FilterRecord record = new FilterRecord();
                RetrieveListMsboRequest request = new RetrieveListMsboRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    CurrentUser = Dao,
                    Filter = record
                };
                var customerRecords = new RetrieveListMsboResponse();
                Thread.Sleep(100 * int.Parse(data));
                customerRecords = serviceClient.Proxy.RetrieveListMsbo(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<UserRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Select(x => new
            {
                id = x.Dao,
                text = data.Equals("1") ? x.FullName : x.Dao
            });
            result = Json(objectItem);
            return result;
        }

        [Authorize]
        [HttpPost]
        public ActionResult ListMSBONameByBranch(string data)
        {
            List<UserRecord> resultCustomer = new List<UserRecord>();
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                FilterRecord record = new FilterRecord();
                record.Branch = CurrentUserRecord.BranchId;
                RetrieveListMsboRequest request = new RetrieveListMsboRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.CustomerManagerController.ListBranch"
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = record
                };
                var customerRecords = new RetrieveListMsboResponse();
                Thread.Sleep(100 * int.Parse(data));
                customerRecords = serviceClient.Proxy.RetrieveListMsbo(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<UserRecord>() : customerRecords.Records;
            }
            JsonResult result = new JsonResult();
            var objectItem = resultCustomer.Select(x => new
            {
                id = x.Dao,
                text = data.Equals("1") ? x.FullName : x.Dao
            });
            result = Json(objectItem);
            return result;
        }

        #endregion
    }
}
